package com.example.lightcamera

import android.widget.TextView
import android.widget.ScrollView
import okhttp3.*
import org.json.JSONObject

class SignalingClient(
    private val serverUrl: String,
    private val listener: Listener,
    private val tvLogs: TextView
) {
    private var webSocket: WebSocket? = null

    interface Listener {
        fun onRoomCreated(roomId: String)
        fun onJoinedRoom(roomId: String)
        fun onConnectRoom(roomId: String)
        fun onMessage(from: String, message: String)
        fun onError(error: String)
    }

    fun connect() {
        log("Connecting to $serverUrl ...")
        val client = OkHttpClient()
        val request = Request.Builder().url(serverUrl).build()
        webSocket = client.newWebSocket(request, object : WebSocketListener() {

            override fun onOpen(webSocket: WebSocket, response: Response) {
                log("Connected to $serverUrl")
                // 创建房间
                val json = JSONObject()
                json.put("action", "create_room")
                webSocket.send(json.toString())
                log("Sent create_room request")
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                log("Recv: $text")
                val msg = JSONObject(text)
                when (msg.optString("type")) {
                    "room_created" -> {
                        listener.onRoomCreated(msg.optString("room_id"))
                        log("Room created: ${msg.optString("room_id")}")
                    }
                    "joined" -> {
                        listener.onJoinedRoom(msg.optString("room_id"))
                        log("Joined room: ${msg.optString("room_id")}")
                    }
                    "room_connect" -> {
                        listener.onConnectRoom(msg.optString("room_id"))
                        log("connect room: ${msg.optString("room_id")}")
                    }
                    "message" -> {
                        listener.onMessage(msg.optString("from"), msg.optString("data"))
                        log("Message from ${msg.optString("from")}: ${msg.optString("data")}")
                    }
                    "error" -> {
                        listener.onError(msg.optString("msg"))
                        log("Error from server: ${msg.optString("msg")}")
                    }
                }
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                val errMsg = t.message ?: "Unknown error"
                listener.onError(errMsg)
                log("Connection failure: $errMsg")
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                log("WebSocket closed: $code $reason")
            }
        })
    }

    fun joinRoom(roomId: String, selfRoomId: String) {
        val json = JSONObject()
        json.put("action", "join_room")
        json.put("room_id", roomId)
        json.put("self_room_id", selfRoomId)
        webSocket?.send(json.toString())
        log("Sent join_room request for $roomId")
    }

    fun sendMessage(to: String, message: String) {
        val json = JSONObject()
        json.put("action", "send")
        json.put("to", to)
        json.put("data", message)
        webSocket?.send(json.toString())
        log("Sent message to $to: $message")
    }

    // 将日志打印到 TextView 上
    private fun log(msg: String) {
        tvLogs.post {
            tvLogs.append("$msg\n")
            (tvLogs.parent as? ScrollView)?.post {
                (tvLogs.parent as ScrollView).fullScroll(ScrollView.FOCUS_DOWN)
            }
        }
    }
}
